package a_aa_amainpackage.qiye_test.address;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

import org.postgresql.copy.CopyManager;
import org.postgresql.core.BaseConnection;

public class jdbcCopyFile {

    public static void main(String args[]) throws Exception {
        System.out.println(copyFromFile(getConnection(), "D:\\zsc\\阿里云\\o2o_stand_company_IDL.csv", "dimension.\"o2o_stand_company_IDL\""));
//        System.out.println(copyFromFile(getConnection(), "C:\\Users\\o2o-rd-0032\\Desktop\\111.csv", "txd.map_txd_brand"));
//        System.out.println(copyFromFile(getConnection(), "C:\\Users\\o2o-rd-0032\\Desktop\\111.csv", "eleme.map_eleme_brand"));
    }

    public static Connection getConnection() throws Exception {
        Class.forName("org.postgresql.Driver").newInstance();
        String host = "hgprecn-cn-m7r1xxicx002-cn-beijing.hologres.aliyuncs.com:80";
        String db = "testdb";
        String user = "LTAI4GDV1WU6ujJXFjWUtfAz";
        String password = "ePJf2wd2BOPOo8JEZUrKFA3aK7Etn0";
        String url = "jdbc:postgresql://"  + host +  "/"  + db + "?reWriteBatchedInserts=true";
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    /**
     * 导入文件至数据库。
     *
     * @param connection
     * @param filePath
     * @param tableName
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public static long copyFromFile(Connection connection, String filePath, String tableName)
            throws SQLException, IOException {
        long count = 0;
        FileInputStream fileInputStream = null;

        try {
            CopyManager copyManager = new CopyManager((BaseConnection) connection);
            fileInputStream = new FileInputStream(filePath);
            count = copyManager.copyIn("COPY " + tableName + " FROM STDIN delimiter ',' csv", fileInputStream);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return count;
    }
}
